package com.three.usermanagement.service.impl;

import com.three.core.entity.Menu;
import com.three.core.vo.R;
import com.three.usermanagement.mapper.MenuMapper;
import com.three.usermanagement.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public R selectRoleMenus(Integer roleId) {
        List<Integer> menu = menuMapper.selectMenuIdsByRoleId(roleId);
        return new R(200, "查询成功", menu);
    }

    @Override
    public R selectRoleMenuIds(Integer roleId) {
        List<Integer> menuIds = menuMapper.selectMenuIdsByRoleId(roleId);
        return new R(200, "查询成功", menuIds);
    }

    @Override
    public R updateRoleMenus(Integer roleId, List<Integer> menuIds) {
        // 先删除用户的所有角色
        int deleteCount = menuMapper.deleteRoleMenusByRoleId(roleId);
        if (deleteCount < 0) {
            return new R(500, "删除旧权限失败", null);
        }

        // 如果新的角色数组不为空，则添加新的角色
        if (menuIds != null && !menuIds.isEmpty()) {
            int insertCount = menuMapper.batchInsertRoleMenus(roleId, menuIds);
            if (insertCount <= 0) {
                return new R(500, "授权失败", null);
            }
        }

        return new R(200, "授权成功", null);
    }

    @Override
    public R selectAllMenus() {
        List<Menu> menus = menuMapper.selectAll();
        return new R(200, "查询成功", buildTreeMenu(menus, 0));
    }

    private List<Menu> buildTreeMenu(List<Menu> menus, Integer parentId) {
        return menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .peek(menu -> menu.setChildren(buildTreeMenu(menus, menu.getMenuId())))
                .collect(Collectors.toList());
    }
}
